<!--
  智慧社区管理系统 - 投诉建议列表页面
  @author Wu.Liang
  @date 2025-06-26
  @version 3.0 - 根据系统设计调整方案重构，独立投诉建议模块
-->
<template>
  <div class="complaint-list-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2 class="page-title">投诉建议管理</h2>
      <div class="page-actions">
        <el-button type="primary" @click="handleCreate" :loading="creating">
          <el-icon><Plus /></el-icon>
          新建投诉
        </el-button>
        <el-button type="success" @click="handleBatchAssign" :loading="assigning">
          <el-icon><User /></el-icon>
          批量分配
        </el-button>
        <el-button type="warning" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索表单 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" @submit.prevent="handleSearch">
        <el-form-item label="社区">
          <el-select
            v-model="searchForm.communityId"
            placeholder="请选择社区"
            clearable
            @change="handleCommunityChange"
            style="width: 200px"
          >
            <el-option
              v-for="item in communityList"
              :key="item.id"
              :label="item.name"
              :value="item.id || 0"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="投诉分类">
          <el-select
            v-model="searchForm.categoryId"
            placeholder="请选择分类"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in categoryList"
              :key="item.id"
              :label="item.name"
              :value="item.id || 0"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="待受理" :value="1" />
            <el-option label="已受理" :value="2" />
            <el-option label="处理中" :value="3" />
            <el-option label="已完成" :value="4" />
            <el-option label="已关闭" :value="5" />
          </el-select>
        </el-form-item>
        <el-form-item label="优先级">
          <el-select
            v-model="searchForm.priority"
            placeholder="请选择优先级"
            clearable
            style="width: 150px"
          >
            <el-option label="低" :value="1" />
            <el-option label="中等" :value="2" />
            <el-option label="高" :value="3" />
            <el-option label="紧急" :value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人员">
          <el-select
            v-model="searchForm.assigneeId"
            placeholder="请选择处理人员"
            clearable
            style="width: 200px"
          >
            <el-option
              v-for="item in assigneeList"
              :key="item.id"
              :label="item.name"
              :value="item.id || 0"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            @change="handleDateRangeChange"
            style="width: 240px"
          />
        </el-form-item>
        <el-form-item label="关键词">
          <el-input
            v-model="searchForm.keyword"
            placeholder="工单号/标题/内容/投诉人"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <div class="table-header">
        <div class="table-title">
          <span>投诉建议列表</span>
          <el-tag :type="getTagType('info')" class="count-tag">共 {{ total }} 条记录</el-tag>
        </div>
        <div class="table-actions">
          <el-button
            type="danger"
            :disabled="!selectedRows.length"
            @click="handleBatchDelete"
          >
            批量删除
          </el-button>
        </div>
      </div>

      <el-table
        v-loading="loading"
        :data="tableData"
        @selection-change="handleSelectionChange"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderNo" label="工单号" width="150" />
        <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="categoryName" label="分类" width="120">
          <template #default="{ row }">
            <el-tag :type="getTagType(getCategoryTagType(row.categoryId))">
              {{ row.categoryName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="userName" label="投诉人" width="100" />
        <el-table-column prop="communityName" label="社区" width="120" />
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getPriorityTagType(row.priority))" :effect="getPriorityEffect(row.priority)">
              {{ getPriorityText(row.priority) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getTagType(getStatusTagType(row.status))" :effect="getStatusEffect(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="assigneeName" label="处理人员" width="100" />
        <el-table-column prop="assignTime" label="分配时间" width="150">
          <template #default="{ row }">
            <span v-if="row.assignTime">{{ formatDate(row.assignTime) }}</span>
            <span v-else class="text-muted">未分配</span>
          </template>
        </el-table-column>
        <el-table-column prop="resolveTime" label="解决时间" width="150">
          <template #default="{ row }">
            <span v-if="row.resolveTime">{{ formatDate(row.resolveTime) }}</span>
            <span v-else class="text-muted">未解决</span>
          </template>
        </el-table-column>
        <el-table-column prop="satisfaction" label="满意度" width="100">
          <template #default="{ row }">
            <el-rate
              v-if="row.satisfaction && row.satisfaction > 0"
              v-model="row.satisfaction"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}"
            />
            <span v-else class="text-muted">未评价</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="280" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="handleViewDetail(row)"
            >
              详情
            </el-button>
            <el-button
              type="success"
              size="small"
              @click="handleAssign(row)"
              :disabled="row.status !== 1"
            >
              分配
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="handleProcess(row)"
              :disabled="!row.assigneeId"
            >
              处理
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleReopen(row)"
              :disabled="row.status !== 4"
            >
              重开
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新建投诉弹窗 -->
    <ComplaintFormDialog
      v-model="formDialogVisible"
      :loading="creating"
      @confirm="handleCreateConfirm"
    />

    <!-- 投诉详情弹窗 -->
    <ComplaintDetailDialog
      v-model="detailDialogVisible"
      :complaint-data="currentComplaint"
      @assign="handleAssign"
      @process="handleProcess"
    />

    <!-- 分配弹窗 -->
    <AssignDialog
      v-model="assignDialogVisible"
      :complaint-data="currentComplaint"
      :loading="assigning"
      @confirm="handleAssignConfirm"
    />

    <!-- 处理弹窗 -->
    <ProcessDialog
      v-model="processDialogVisible"
      :complaint-data="currentComplaint"
      :loading="processing"
      @confirm="handleProcessConfirm"
    />

    <!-- 重开弹窗 -->
    <ReopenDialog
      v-model="reopenDialogVisible"
      :complaint-data="currentComplaint"
      :loading="reopening"
      @confirm="handleReopenConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Plus, 
  User, 
  Download, 
  Search, 
  Refresh
} from '@element-plus/icons-vue'
import type { Complaint, ComplaintQueryParams } from './types/complaint'
import { complaintApi, complaintCategoryApi } from '@/api/complaint'
import { commonApi } from '@/api/property'
import ComplaintFormDialog from './components/ComplaintFormDialog.vue'
import ComplaintDetailDialog from './components/ComplaintDetailDialog.vue'
import AssignDialog from './components/AssignDialog.vue'
import ReopenDialog from './components/ReopenDialog.vue'
import ProcessDialog from './components/ProcessDialog.vue'
import { showSuccess, showError, showWarning, showInfo } from '@/utils/message'
import { getTagType } from '@/utils/message'

// 作者: Wu.Liang

// 响应式数据
const loading = ref(false)
const creating = ref(false)
const assigning = ref(false)
const reopening = ref(false)
const processing = ref(false)

// 表格数据
const tableData = ref<Complaint[]>([])
const selectedRows = ref<Complaint[]>([])
const total = ref(0)

// 分页数据
const pagination = reactive({
  current: 1,
  size: 20
})

// 搜索表单 - 根据新接口调整，修复Element Plus警告
const searchForm = reactive<ComplaintQueryParams>({
  communityId: null,
  categoryId: null,
  status: null,
  priority: null,
  assigneeId: null,
  startDate: null,
  endDate: null,
  keyword: ''
})

// 日期范围
const dateRange = ref<[string, string] | null>(null)

// 下拉选项数据
const communityList = ref<any[]>([])
const categoryList = ref<any[]>([])
const assigneeList = ref<any[]>([])

// 弹窗控制
const formDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const assignDialogVisible = ref(false)
const processDialogVisible = ref(false)
const reopenDialogVisible = ref(false)

// 当前操作的投诉
const currentComplaint = ref<Complaint | null>(null)

// 计算属性 - 根据新接口调整
const queryParams = computed(() => ({
  ...searchForm,
  current: pagination.current,
  size: pagination.size
}))

// 生命周期
onMounted(() => {
  loadData()
  loadCommunityList()
  loadCategoryList()
  loadAssigneeList()
})

// 加载数据 - 使用静态数据模拟
const loadData = async () => {
  try {
    loading.value = true
    
    // 模拟API延迟
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 静态数据模拟
    const mockData = {
      records: [
        {
          id: 1,
          orderNo: 'C202501010001',
          userId: 1,
          communityId: 1,
          categoryId: 1,
          title: '电梯故障投诉',
          content: '电梯经常出现故障，影响居民出行安全',
          status: 1,
          priority: 3,
          assigneeId: null,
          assignTime: null,
          resolveTime: null,
          satisfaction: null,
          createTime: '2025-01-01 09:00:00',
          updateTime: '2025-01-01 09:00:00',
          userName: '张先生',
          communityName: '阳光花园',
          categoryName: '设施设备',
          assigneeName: null,
          statusName: '待受理',
          priorityName: '高'
        },
        {
          id: 2,
          orderNo: 'C202501010002',
          userId: 2,
          communityId: 1,
          categoryId: 2,
          title: '噪音扰民投诉',
          content: '楼上住户装修噪音过大，影响正常休息',
          status: 2,
          priority: 2,
          assigneeId: 1,
          assignTime: '2025-01-01 10:00:00',
          resolveTime: null,
          satisfaction: null,
          createTime: '2025-01-01 08:30:00',
          updateTime: '2025-01-01 10:00:00',
          userName: '李女士',
          communityName: '阳光花园',
          categoryName: '噪音污染',
          assigneeName: '王管理员',
          statusName: '已受理',
          priorityName: '中等'
        },
        {
          id: 3,
          orderNo: 'C202501010003',
          userId: 3,
          communityId: 2,
          categoryId: 3,
          title: '停车位管理建议',
          content: '建议增加停车位数量，解决停车难问题',
          status: 4,
          priority: 1,
          assigneeId: 2,
          assignTime: '2025-01-01 11:00:00',
          resolveTime: '2025-01-02 15:00:00',
          satisfaction: 5,
          createTime: '2025-01-01 07:00:00',
          updateTime: '2025-01-02 15:00:00',
          userName: '赵先生',
          communityName: '绿城小区',
          categoryName: '管理服务',
          assigneeName: '刘管理员',
          statusName: '已完成',
          priorityName: '低'
        }
      ],
      total: 3,
      size: 20,
      current: 1,
      pages: 1
    }
    
    tableData.value = mockData.records
    total.value = mockData.total
    
  } catch (error) {
    console.error('加载投诉数据失败:', error)
    showError('加载数据失败')
  } finally {
    loading.value = false
  }
}

// 加载社区列表 - 使用静态数据
const loadCommunityList = async () => {
  try {
    // 静态数据模拟
    communityList.value = [
      { id: 1, name: '阳光花园' },
      { id: 2, name: '绿城小区' },
      { id: 3, name: '金桂苑' },
      { id: 4, name: '银桂苑' }
    ]
  } catch (error) {
    console.error('加载社区列表失败:', error)
  }
}

// 加载分类列表 - 使用静态数据
const loadCategoryList = async () => {
  try {
    // 静态数据模拟
    categoryList.value = [
      { id: 1, name: '设施设备' },
      { id: 2, name: '噪音污染' },
      { id: 3, name: '管理服务' },
      { id: 4, name: '环境卫生' },
      { id: 5, name: '安全保卫' }
    ]
  } catch (error) {
    console.error('加载分类列表失败:', error)
  }
}

// 加载处理人员列表 - 使用静态数据
const loadAssigneeList = async () => {
  try {
    // 静态数据模拟
    assigneeList.value = [
      { id: 1, name: '王管理员' },
      { id: 2, name: '刘管理员' },
      { id: 3, name: '陈管理员' },
      { id: 4, name: '李管理员' }
    ]
  } catch (error) {
    console.error('加载处理人员列表失败:', error)
  }
}

// 事件处理
const handleSearch = () => {
  pagination.current = 1
  loadData()
}

const handleReset = () => {
  Object.assign(searchForm, {
    communityId: null,
    categoryId: null,
    status: null,
    priority: null,
    assigneeId: null,
    startDate: null,
    endDate: null,
    keyword: ''
  })
  dateRange.value = null
  pagination.current = 1
  loadData()
}

const handleCommunityChange = (communityId: number) => {
  // 可以在这里加载该社区的处理人员列表
}

const handleDateRangeChange = (range: [string, string] | null) => {
  if (range) {
    searchForm.startDate = range[0]
    searchForm.endDate = range[1]
  } else {
    searchForm.startDate = null
    searchForm.endDate = null
  }
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.current = 1
  loadData()
}

const handleCurrentChange = (current: number) => {
  pagination.current = current
  loadData()
}

const handleSelectionChange = (rows: Complaint[]) => {
  selectedRows.value = rows
}

// 新建投诉
const handleCreate = () => {
  formDialogVisible.value = true
}

const handleCreateConfirm = async (data: any) => {
  try {
    creating.value = true
    const response = await complaintApi.createComplaint(data)
    if (response.code === 200) {
      showSuccess('投诉创建成功')
      formDialogVisible.value = false
      loadData()
    } else {
      showError(response.message || '创建投诉失败')
    }
  } catch (error) {
    console.error('创建投诉失败:', error)
    showError('创建投诉失败')
  } finally {
    creating.value = false
  }
}

// 查看详情
const handleViewDetail = (row: Complaint) => {
  currentComplaint.value = row
  detailDialogVisible.value = true
}

// 分配
const handleAssign = (row: Complaint) => {
  currentComplaint.value = row
  assignDialogVisible.value = true
}

const handleAssignConfirm = async (data: any) => {
  try {
    assigning.value = true
    const response = await complaintApi.assignComplaint(currentComplaint.value!.id, data)
    if (response.code === 200) {
      showSuccess('分配成功')
      assignDialogVisible.value = false
      loadData()
    } else {
      showError(response.message || '分配失败')
    }
  } catch (error) {
    console.error('分配失败:', error)
    showError('分配失败')
  } finally {
    assigning.value = false
  }
}

// 处理
const handleProcess = (row: Complaint) => {
  currentComplaint.value = row
  processDialogVisible.value = true
}

const handleProcessConfirm = async (data: any) => {
  try {
    processing.value = true
    const response = await complaintApi.processComplaint(currentComplaint.value!.id, data)
    if (response.code === 200) {
      showSuccess('处理成功')
      processDialogVisible.value = false
      loadData()
    } else {
      showError(response.message || '处理失败')
    }
  } catch (error) {
    console.error('处理失败:', error)
    showError('处理失败')
  } finally {
    processing.value = false
  }
}

// 批量分配
const handleBatchAssign = async () => {
  if (selectedRows.value.length === 0) {
    showWarning('请选择要分配的投诉')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要对选中的 ${selectedRows.value.length} 条投诉进行批量分配吗？`,
      '批量分配确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 这里需要实现批量分配逻辑
    showWarning('批量分配功能待实现')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量分配失败:', error)
      showError('批量分配失败')
    }
  }
}

// 删除
const handleDelete = async (row: Complaint) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条投诉记录吗？删除后无法恢复。',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    const response = await complaintApi.deleteComplaint(row.id)
    if (response.code === 200) {
      showSuccess('删除成功')
      loadData()
    } else {
      showError(response.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      showError('删除失败')
    }
  }
}

// 批量删除
const handleBatchDelete = async () => {
  if (selectedRows.value.length === 0) {
    showWarning('请选择要删除的投诉')
    return
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedRows.value.length} 条投诉记录吗？删除后无法恢复。`,
      '批量删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 这里需要后端提供批量删除接口
    showWarning('批量删除功能待实现')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      showError('批量删除失败')
    }
  }
}

// 导出
const handleExport = () => {
  showInfo('导出功能待实现')
}

// 重开
const handleReopen = (row: Complaint) => {
  currentComplaint.value = row
  reopenDialogVisible.value = true
}

const handleReopenConfirm = async (data: { reason: string }) => {
  if (!currentComplaint.value) return
  
  try {
    reopening.value = true
    const response = await complaintApi.reopenComplaint(currentComplaint.value.id, data.reason)
    if (response.code === 200) {
      showSuccess('投诉重开成功')
      reopenDialogVisible.value = false
      loadData()
    } else {
      showError(response.message || '重开失败')
    }
  } catch (error) {
    console.error('重开失败:', error)
    showError('重开失败')
  } finally {
    reopening.value = false
  }
}

// 工具方法 - 根据新接口调整
const getCategoryTagType = (categoryId: number): 'success' | 'warning' | 'info' | 'error' | 'danger' => {
  const typeMap: { [key: number]: string } = {
    1: 'primary',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return (typeMap[categoryId] || 'info') as 'success' | 'warning' | 'info' | 'error' | 'danger'
}

const getPriorityTagType = (priority: number): 'success' | 'warning' | 'info' | 'error' | 'danger' => {
  const typeMap: { [key: number]: string } = {
    1: 'info',
    2: 'success',
    3: 'warning',
    4: 'danger'
  }
  return (typeMap[priority] || 'info') as 'success' | 'warning' | 'info' | 'error' | 'danger'
}

const getPriorityEffect = (priority: number) => {
  return priority === 4 ? 'dark' : 'light'
}

const getPriorityText = (priority: number) => {
  const textMap: { [key: number]: string } = {
    1: '低',
    2: '中等',
    3: '高',
    4: '紧急'
  }
  return textMap[priority] || '未知'
}

const getStatusTagType = (status: number): 'success' | 'warning' | 'info' | 'error' | 'danger' => {
  const typeMap: { [key: number]: string } = {
    1: 'warning',
    2: 'primary',
    3: 'info',
    4: 'success',
    5: 'danger'
  }
  return (typeMap[status] || 'info') as 'success' | 'warning' | 'info' | 'error' | 'danger'
}

const getStatusEffect = (status: number) => {
  return status === 4 ? 'dark' : 'light'
}

const getStatusText = (status: number) => {
  const textMap: { [key: number]: string } = {
    1: '待受理',
    2: '已受理',
    3: '处理中',
    4: '已完成',
    5: '已关闭'
  }
  return textMap[status] || '未知'
}

const formatDate = (date: string) => {
  if (!date) return ''
  return new Date(date).toLocaleDateString()
}
</script>

<style scoped>
.complaint-list-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-title {
  margin: 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-actions {
  display: flex;
  gap: 10px;
}

.search-card {
  margin-bottom: 20px;
}

.table-card {
  margin-bottom: 20px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.table-title {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 600;
}

.count-tag {
  font-size: 12px;
}

.table-actions {
  display: flex;
  gap: 10px;
}

.pagination-wrapper {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}
</style> 